package com.threeox.commonlibrary.util.sql;

import android.database.Cursor;

import com.threeox.commonlibrary.entity.engine.model.table.TableResultMessage;
import com.threeox.commonlibrary.util.sql.impl.ITableSqlExecutor;
import com.threeox.ormlibrary.impl.SqlExecutor;
import com.threeox.utillibrary.util.EmptyUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 
 * @ClassName: TableSqlExecutor
 * 
 * @Description: TODO(自定义表格的Sql执行器)
 * 
 * @author 赵屈犇
 * 
 * @date 创建时间: 2017/8/14 18:14
 * 
 * @version 1.0
 * 
 */
public class TableSqlExecutor extends SqlExecutor implements ITableSqlExecutor {


    public static TableSqlExecutor newInstance() {
        return new TableSqlExecutor();
    }

    /**
     * 得到表格集合数据
     *
     * @param sql
     * @param clazz
     * @param selectionArgs
     * @param <T>
     * @return
     */
    @Override
    public <T> TableResultMessage<T> queryTableResult(String sql, String countSql ,Class clazz, String... selectionArgs) throws Exception{
        TableResultMessage<T> result = new TableResultMessage<T>();
        List<T> datas = queryList(result, sql, clazz, selectionArgs);
        result.setDatas(datas);
        if (EmptyUtils.isNotEmpty(countSql)) {
            Long count = queryCount(countSql, selectionArgs);
            result.setCount(count);
            result.setPageSize((count  +  20  - 1) / 20);
        }
        return result;
    }

    public <T> List<T> queryList(TableResultMessage result, String sql, Class clazz, String... selectionArgs) {
        Cursor cursor = getReadableDatabase().rawQuery(sql, selectionArgs);
        return cursorToList(cursor, clazz, result);
    }

    public List cursorToList(Cursor cursor, Class clazz, TableResultMessage result) {
        if (cursor != null) {
            String[] columnNames = cursor.getColumnNames();
            List<String> columns = new ArrayList<String>();
            if (EmptyUtils.isNotEmpty(columnNames)) {
                for (String columnName : columnNames) {
                    columns.add(columnName);
                }
            }
            result.setColumnNames(columns);
        }
        return super.cursorToList(cursor, clazz);
    }
}
